package com.securityLearn.securityAuth.config.security;

import com.securityLearn.securityAuth.service.UserApi;
import com.securityLearn.securityAuth.service.entity.UserDto;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

/**
 * Security form表单验证，查询用户数据的实现类
 * @author duzq
 * @date 2021-09-04 14:03:51
 */
@Component
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private UserApi userApi;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 查询用户
        UserDto user = userApi.getUserByUserName(username);
        if (user == null) {
            return null;
        }
        // 返回
        UserDetails userDetails = User.withUsername(user.getUserName())
                                        .password(user.getPassword())
                                        .authorities("default")
                                        .build();
        return userDetails;
    }
}
